import { createRouter, createWebHashHistory } from 'vue-router'
import { useStore } from '../store'
const routes = [
    {
        path: '/',
        name: 'Home',
        component: () => import("../views/home.vue")
    },
    {
        path: '/login',
        name: 'login',
        component: () => import("../views/login.vue")
    },
    {
        path:'/register',
        name:'register',
        component:()=>import('../views/register.vue')
    },
    {
        path:'/forgot',
        name:'forgot',
        component:()=>import('../views/forgot.vue')
    },
    {
        path: '/community',
        name: 'community',
        component: () => import("../views/community.vue")
    },
    {
        path: '/userInfo',
        name: 'userInfo',
        component: () => import("../views/userInfo.vue")
    }, {
        path: '/test',
        name: 'test',
        component: () => import("../views/template.vue")
    },
    {
        path: '/publish',
        name: 'publish',
        component: () => import("../views/publish.vue")
    },
    {
        path: '/system',
        name: 'system',
        component: () => import("../views/system/index.vue"),
        children: [
            {
              path: 'user',
              component: ()=>import('../views/system/user.vue'),
            },
            {
                path:"all",
                component:()=>import('../views/system/all.vue')
            },
            {
                path:'comment',
                component:()=>import('../views/system/comment.vue')
            },
            {
                path:'like',
                component:()=>import('../views/system/like.vue')
            },
            {
                path:'post',
                component:()=>import('../views/system/post.vue')
            }
          ],
    },
    {
        path: '/404',
        name: '404',
        component: () => import("../views/404.vue")
    },
    {
        path: '/401',
        name: '401',
        component: () => import("../views/401.vue")
    },
    {
        path:'/other',
        name:"other",
        component:()=> import('../views/other.vue')
    }
]

const router = createRouter({
    history: createWebHashHistory(),
    routes,
})
router.beforeEach((to, from, next) => {
    const store = useStore()
    const user = store.getUserInfo()
    if (to.matched.length === 0) {
        next({ path: '/404' })
    } 
    else if (to.path === '/system') {
        console.log('no permission')
        if (user.role !== 'admin') {
            next('/401')
        }
        else {
            next()
        }
    }
    else if (
        store.token || to.path === '/login' || to.path === '/' || to.path ==='/other' || to.path ==='/register' || to.path ==='/forgot'
    ) { next() }

    else {
        next({ path: '/login' })
    }
})
export default router